<template>
  <div class="words-manage">
    <div class="words-manage-wrap">
      <div class="search">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item>
            <el-input size="small" v-model="searchInput" placeholder="请输入内容"
                      @keyup.enter.native="handleSearch"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleSearch()">搜索</el-button>
          </el-form-item>
          <el-button :loading="downloadLoading" style="margin:0 0 20px 20px; position:absolute; right:100px;"
                     type="primary" icon="el-icon-document" @click="handleDownload">导出全部
          </el-button>

        </el-form>
      </div>

      <div class="op-area">
            <el-button class="addButton" size="mini" icon="el-icon-document" @click="addClick">新增</el-button>
      </div>

      <div class="table-area">
          <el-table
            :data="tableList"
            v-loading="listLoading" border row-key="id" :tree-props="{children: 'children'}" class="table">
            <el-table-column label="ID" prop="id" width="100"></el-table-column>
            <el-table-column label="词语" prop="keyword" width="200">
                <template slot-scope="scope">
                    <span v-if="scope.row.wordFreamIds && scope.row.wordFreamIds.length > 1" style="color:#409EFF">{{scope.row.keyword}}</span>
                    <span v-else>{{scope.row.keyword}}</span>
                </template>
            </el-table-column>
            <el-table-column label="一级" prop="wordFreamLeve1" width="200"></el-table-column>
            <el-table-column label="二级" prop="wordFreamLeve2" width="200"></el-table-column>
            <el-table-column label="三级" prop="wordFreamLeve3" width="200"></el-table-column>
            <!--            <el-table-column label="四级" prop="wordFreamLeve4" width="200"></el-table-column>-->
            <el-table-column label="操作">
              <template slot-scope="scope" v-if="scope.row.addBtn">
                <el-button @click="editClick(scope.row)" type="text" size="small">编辑</el-button>
                <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.limit"
              @pagination="getTableData"
            />
          </div>
      </div>
    </div>


    <el-dialog title="词表修改" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" size="small">
        <el-form-item label="词语" :label-width="formLabelWidth">
          <el-input v-model="form.keyword" auto-complete="off" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="所属框架" :label-width="formLabelWidth">
            <el-container v-for="(item,idx) in form.wordFreamIds" :key="idx">
              <el-row :gutter="20">
                  <el-col :span="16">
                        <tree-select :options="wordsTree"  :normalizer="treeNormalizer"  placeholder="请选择分类..." 
                              v-model="form.wordFreamIds[idx]"/>
                  </el-col>
                  <el-col :span="8"><el-button @click="dialogForm_delFrame(idx)">删除</el-button></el-col>
              </el-row>
            </el-container>
            <el-button @click="dialogForm_addFrame(idx)">添加</el-button>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialog_handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {addWord, delWord, getWordsList, addWordReal} from '@/api/word-manage-list'
  import {getWordsTree} from '@/api/words-fream-tree'
  import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  let _ = require('lodash')

  export default {
    name: 'MarkdownDemo',
    components: {Pagination, TreeSelect},
    data() {
      return {
        tableList: [],
        searchInput: '',
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10
        },

        wordsTree: [],
        wordsTree_selected: [],
        //treeOptions:[],

        dialogFormVisible: false,
        formLabelWidth: '120px',
        form: {
          id: '',
          keyword: '',
          wordFreamIds: [],
          //wordFreamOldId: [],
          //wordFreamCurrentId: null,
          //add: false,
        },

        downloadLoading: false,

      }
    },
    computed: {},
    created() {
      this.getTableData();
      this.getWordsTree();

    },
    methods: {
      handleSearch() {
        this.listQuery.page = 1;
        this.getTableData();
      },
      getTableData() {
        this.listLoading = true;
        let param = {
          pageSize: this.listQuery.limit,
          pageNum: this.listQuery.page,
          key: this.searchInput,
        };
        getWordsList(param).then(res => {
          this.tableList = res.result.list;
          let wordFrame = [];
          // 格式化
          for (let i = 0; i < this.tableList.length; i++) {
            const firstFrameItem = this.tableList[i].wordFreamIteams[0]; // 将挂靠的第一个框架作为父 格式化数据要求
            wordFrame.push({
                id: this.tableList[i].id,
                keyword: this.tableList[i].keyword,
                addBtn: true,
                wordFreamIds: [],
                wordFreamLeve1: firstFrameItem?.wordFreamLeve1,
                wordFreamLeve1Id: firstFrameItem?.wordFreamLeve1Id,
                wordFreamLeve2: firstFrameItem?.wordFreamLeve2,
                wordFreamLeve2Id: firstFrameItem?.wordFreamLeve2Id,
                wordFreamLeve3: firstFrameItem?.wordFreamLeve3,
                wordFreamLeve3Id: firstFrameItem?.wordFreamLeve3Id,
                wordFreamLeve4: firstFrameItem?.wordFreamLeve4,
                wordFreamLeve4Id: firstFrameItem?.wordFreamLeve4Id,
                children: []
              }
            );
            const wordFrameIdItemFirst = wordFrame[i]?.wordFreamLeve4Id || wordFrame[i]?.wordFreamLeve3Id || wordFrame[i]?.wordFreamLeve2Id || wordFrame[i]?.wordFreamLeve1Id
            if (wordFrameIdItemFirst) {
              wordFrame[i].wordFreamIds.push(wordFrameIdItemFirst);
            }
            const frames = this.tableList[i].wordFreamIteams;
            for (let j = 1; j < frames.length; j++) {
              // 当id不会出现0时，代码成立
              const wordFrameIdItem = frames[j]?.wordFreamLeve4Id || frames[j]?.wordFreamLeve3Id || frames[j]?.wordFreamLeve2Id || frames[j]?.wordFreamLeve1Id

              wordFrame[i].children.push({
                id: this.tableList[i].id + '-' + j,
                keyword: this.tableList[i].keyword,
                addBtn: false,
                wordFreamLeve1: frames[j]?.wordFreamLeve1,
                wordFreamLeve1Id: frames[j]?.wordFreamLeve1Id,
                wordFreamLeve2: frames[j]?.wordFreamLeve2,
                wordFreamLeve2Id: frames[j]?.wordFreamLeve2Id,
                wordFreamLeve3: frames[j]?.wordFreamLeve3,
                wordFreamLeve3Id: frames[j]?.wordFreamLeve3Id,
                wordFreamLeve4: frames[j]?.wordFreamLeve4,
                wordFreamLeve4Id: frames[j]?.wordFreamLeve4Id,
              });
              if (wordFrameIdItem) {
                wordFrame[i].wordFreamIds.push(wordFrameIdItem);
              }
            }

          }
          console.log(wordFrame);
          this.tableList = wordFrame;
          //this.tableTagList = res.result.list[0].newPolicyKeywordList;
          this.total = res.result.total;
          this.listLoading = false;
        })
      },

      treeNormalizer(node){
          //去掉children=null的属性
          if(node.children==null||node.children=='null'){
              delete node.children;
          }
      },

      // 只获取一次
      getWordsTree() {
        getWordsTree().then(res => {
          this.wordsTree = res.result;
        });
      },
      handleDelete(row) {
        console.log('[handleDelete]', row);
        this.$confirm("确定删除?", {type: "warning"}).then(() => {
            this.listLoading = true;
            delWord({id: row.id}).then(res => {
                this.$message({ type: 'success', message: '删除成功' });
                this.getTableData();
            }).catch(error => {
                this.$message({ type: 'error', message: '删除失败' });
            })
        }).catch(() => {})


      },
      editClick(row) {
        this.form.id = row.id;
        //this.form.add = false;
        this.form.keyword = row.keyword;
        if (row.wordFreamIds) {
          this.form.wordFreamIds = [...row.wordFreamIds];
        } else {
          this.form.wordFreamIds = [];
        }
        console.log('[editClick]', row);
        this.dialogFormVisible = true;
      },
        // 新增关键词
      addClick(){
        this.form.id = 0;
        //this.form.add = false;
        this.form.keyword = '';
        this.form.wordFreamIds = [];
        this.form.wordFreamCurrentId = null;
        this.dialogFormVisible = true;
      },



      handleDownload() {
        this.listLoading = true;
        this.downloadLoading = true

        getWordsList({pageSize: 10000}).then(res => {

          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['keyworkd']
            const filterVal = ['keyword']
            const list = res.result.list
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '关键词',
              autoWidth: true,
              bookType: 'txt'
            })
            this.downloadLoading = false
          })

          this.listLoading = false;
        })

      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },



      dialogForm_delFrame(idx){
        this.form.wordFreamIds.splice( idx, 1 );
      },
      dialogForm_addFrame(){
          // 这里必须添加null或undefined。 空字符串会导致treeselect报错。
        this.form.wordFreamIds.push( undefined );
      },

      dialog_handleSubmit() {
          // 先去重。再去掉未选择的。treeselect未选择时是undefined
        let arr2 = Array.from( new Set(this.form.wordFreamIds) );
        this.form.wordFreamIds = arr2.filter(function(item) { return !!item });

        //console.log('[dialog_handleSubmit]', this.form);return;

        if (this.form.id) {     // 新增/编辑绑定关系
            this.listLoading = true;

              // 提交时的字段: id,add,keyword,wordFreamIds
            addWord(this.form).then(res => {
                this.dialogFormVisible = false
                this.getTableData();
                //this.listLoading = false;
            }).catch(error => {
                this.listLoading = false;
            })
        }else{          // 直接添加关键词
            this.listLoading = true;

              // 提交时的字段: id=0,keyword,wordFreamIds
            addWordReal(this.form).then(res => {
                this.dialogFormVisible = false
                this.getTableData();
                //this.listLoading = false;
            }).catch(error => {
                this.listLoading = false;
            })
        }
      },
    }
  }
</script>

<style lang="less" scoped>
.words-manage {
    padding-top: 36px;

    .words-manage-wrap {
      width: 90%;
      margin: auto;
    }

    .search {
      width: 300px;
      display: flex;
      margin-bottom: 24px;
    }

    .op-area {
      margin-bottom: 24px;
    }


    .el-container{
      margin-bottom:5px;
    }

}
</style>
